<template>
    <div>
        <div style="margin-bottom: 5px">
            <el-input v-model="inputName" placeholder="please input name" style="width: 200px" suffix-icon="el-icon-search"
                      @keyup.enter.native="loadPost">
            </el-input>
            <el-select v-model="selectGoodstype" placeholder="请选择种类" style="margin-left: 7px">
                <el-option
                        v-for="item in goodstypeData"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                </el-option>
            </el-select>
            <el-select v-model="selectStorage" placeholder="请选择仓库" style="margin-left: 7px">
                <el-option
                        v-for="item in storageData"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                </el-option>
            </el-select>

            <el-button type="success" style="margin-left: 7px" @click="loadPost">查询</el-button>
            <el-button type="primary" @click="reset">重置</el-button>
            <el-button type="success" style="margin-left: 7px" @click="addGoods" v-if="user.roleId == 0">新增</el-button>
            <el-button type="primary" style="margin-left: 7px" @click="inGoods" v-if="user.roleId != 2">入库</el-button>
            <el-button type="success" style="margin-left: 7px" @click="outGoods" v-if="user.roleId != 2">出库</el-button>
        </div>

        <el-table :data="tableData" :stripe="stripeTrue" :border="borderTrue"
                  :header-cell-style="{background:'rgba(209,209,245,0.28)'}"
                  highlight-current-row
                  @current-change="selectGoodsCurrentChange">

            <el-table-column prop="id" label="ID" width="">
            </el-table-column>
            <el-table-column prop="name" label="品名" width="">
            </el-table-column>
            <el-table-column prop="goodstype" label="分类" width="" :formatter="goods_goodstype">
            </el-table-column>
            <el-table-column prop=storage label="仓库" width="" :formatter="goods_storage">
            </el-table-column>
            <el-table-column prop="count" label="数量" width="">
            </el-table-column>
            <el-table-column prop="remark" label="备注" width="">
            </el-table-column>

            <el-table-column prop="operate" label="操作" width="" v-if="user.roleId != 2">
                <template slot-scope="scope">
                    <el-button size="small" type="success" @click="mod(scope.row)">编辑</el-button>

                    <el-popconfirm style="margin-left: 5px"
                                   confirm-button-text='确定'
                                   cancel-button-text='取消'
                                   icon="el-icon-question"
                                   icon-color="#cebdee"
                                   title="确定删除吗?"
                                   @confirm="del(scope.row.id)"
                    >
                        <el-button slot="reference" size="small" type="danger">删除</el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination style="margin-top: 5px; text-align: center"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       :current-page="pageNum"
                       :page-sizes="[7, 10, 15,20]"
                       :page-size="pageSize"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="total">
        </el-pagination>

        <el-dialog
                :title="addOrUpdate + ''"
                :visible.sync="centerDialogVisible"
                width="30%"
                :before-close="handleClose"
                center>

            <el-form ref="form" :rules="rules" :model="form" label-width="80px">
                <el-form-item label="品名：" prop="name">
                    <el-col :span="20">
                        <el-input v-model="form.name"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="种类：" prop="goodstype">
                    <el-col :span="20">
                        <el-select v-model="form.goodstype" placeholder="请选择种类">
                            <el-option
                                    v-for="item in goodstypeData"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                    </el-col>
                </el-form-item>
                <el-form-item label="仓库：" prop="storage">
                    <el-col :span="20">
                        <el-select v-model="form.storage" placeholder="请选择仓库">
                            <el-option
                                    v-for="item in storageData"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                    </el-col>
                </el-form-item>
                <el-form-item label="数量：" prop="count">
                    <el-col :span="20">
                        <el-input v-model="form.count"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="备注：" prop="remark">
                    <el-col :span="20">
                        <el-input type="textarea" v-model="form.remark"></el-input>
                    </el-col>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
    <el-button @click="centerDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveAdd">确 定</el-button>
   </span>
        </el-dialog>

<!--    入库：    -->

        <el-dialog
                :title="addOrUpdate + ''"
                :visible.sync="inGoodsDialogVisible"
                width="30%"
                :before-close="handleClose"
                center>
            <!--选择出入库申请人 嵌套对话框-->
            <el-dialog
                    width="60%"
                    title="选择申请人"
                    :visible.sync="innerVisible"
                    append-to-body
                    center>

                    <!--导入选择用户页面-->
                    <SelectUser @doSelectUser="doSelectUser"></SelectUser>

                    <span slot="footer" class="dialog-footer">
                        <el-button @click="innerVisible = false">取 消</el-button>
                        <el-button type="primary" @click="confirmUser">确 定</el-button>
                    </span>
            </el-dialog>

            <el-form ref="inGoodsForm" :rules="inGoodsRules" :model="inGoodsForm" label-width="80px">
                <el-form-item label="申请人：" prop="userName">
                    <el-col :span="20">
                        <el-input v-model="inGoodsForm.userName" readonly @click.native="selectUser"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="品名：">
                    <el-col :span="20">
                        <el-input v-model="inGoodsForm.goodsName" readonly></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="种类：">
                    <el-col :span="20">
                        <el-input v-model="inGoodsForm.goodsType" :formatter="goods_goodstype" readonly></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="仓库：">
                    <el-col :span="20">
                        <el-input v-model="inGoodsForm.storage" :formatter="goods_storage" readonly></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="数量：" prop="count">
                    <el-col :span="20">
                        <el-input v-model="inGoodsForm.count"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="备注：" prop="remark">
                    <el-col :span="20">
                        <el-input type="textarea" v-model="inGoodsForm.remark"></el-input>
                    </el-col>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="inGoodsDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="doInGoods">确 定</el-button>
            </span>
        </el-dialog>

        <!--    出库：    -->

        <el-dialog
                :title="addOrUpdate + ''"
                :visible.sync="outGoodsDialogVisible"
                width="30%"
                :before-close="handleClose"
                center>
            <!--选择出入库申请人 嵌套对话框-->
            <el-dialog
                    width="60%"
                    title="选择申请人"
                    :visible.sync="innerVisible"
                    append-to-body
                    center>
                <!--导入选择用户页面-->
                <SelectUser @doSelectUser="doSelectUser"></SelectUser>

                <span slot="footer" class="dialog-footer">
                        <el-button @click="innerVisible = false">取 消</el-button>
                        <el-button type="primary" @click="confirmUser">确 定</el-button>
                    </span>
            </el-dialog>

            <el-form ref="outGoodsForm" :rules="outGoodsRules" :model="outGoodsForm" label-width="80px">
                <el-form-item label="申请人：" prop="userName">
                    <el-col :span="20">
                        <el-input v-model="outGoodsForm.userName" readonly @click.native="selectUser"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="品名：">
                    <el-col :span="20">
                        <el-input v-model="outGoodsForm.goodsName" readonly></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="种类：">
                    <el-col :span="20">
                        <el-input v-model="outGoodsForm.goodsType" :formatter="goods_goodstype" readonly></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="仓库：">
                    <el-col :span="20">
                        <el-input v-model="outGoodsForm.storage"  :formatter="goods_storage" readonly></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="数量：" prop="count">
                    <el-col :span="20">
                        <el-input v-model="outGoodsForm.count"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="备注：" prop="remark">
                    <el-col :span="20">
                        <el-input type="textarea" v-model="outGoodsForm.remark"></el-input>
                    </el-col>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="outGoodsDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="doOutGoods">确 定</el-button>
            </span>
        </el-dialog>
    </div>

</template>

<script>
    import SelectUser from "@/components/goods/SelectUser";
    import RecordManage from "@/components/record/RecordManage";
    export default {
        name: "GoodsManage",
        components: {SelectUser,RecordManage},

        data() {

            let checkCount = (rule, value, callback) => {
                if(value>9999){
                    callback(new Error('数量输入过大'));
                }else{
                    callback();
                }
            };

            let checkOutCount = (rule, value, callback) => {
                if(value>this.form.count){
                    value = null;
                    callback(new Error('出库数量大于总数'));
                }else{
                    callback();
                }
            };


            return {

                user: JSON.parse(sessionStorage.getItem("CurUser")),

                tableData: [],
                storageData: [],
                goodstypeData: [],
                stripeTrue:true,
                borderTrue:true,
                pageSize: 10,
                pageNum: 1,
                total:0,
                inputName:'',
                selectGoodstype: '',
                selectStorage: '',
                currentRow: {},
                tempUser:{},

                addOrUpdate:String,

                centerDialogVisible:false,
                inGoodsDialogVisible: false,
                innerVisible: false,
                outGoodsDialogVisible: false,

                form:{
                    name: '',
                    storage: '',
                    goodstype: '',
                    count: '',
                    remark:'',
                },

                inGoodsForm:{
                    goods: '',
                    goodsName:'',
                    userName: '',
                    goodsType:'',
                    storage:'',
                    count: '',
                    remark:'',
                    userId: '',
                    adminId: '',
                    status: ''
                },
                outGoodsForm: {
                    goods: '',
                    goodsName:'',
                    userName: '',
                    goodsType:'',
                    storage:'',
                    count: '',
                    remark:'',
                    userId: '',
                    adminId: '',
                    status: ''
                },

                inGoodsRules:{

                    userName: [
                        {required: true, message: '请选择入库申请人', trigger: 'blur'},
                    ],
                    count: [
                        {required: true, message: '请输入入库数量', trigger: 'blur'},
                        {pattern: /^([1-9][0-9]*){1,4}$/,message: '数量必须为正整数字',trigger: "blur"},
                        {validator:checkCount,trigger: 'blur'}
                    ]
                },
                outGoodsRules:{

                    userName: [
                        {required: true, message: '请选择出库申请人', trigger: 'blur'},
                    ],
                    count: [
                        {required: true, message: '请输入出库数量', trigger: 'blur'},
                        {pattern: /^([1-9][0-9]*){1,4}$/,message: '数量必须为正整数字',trigger: "blur"},
                        {validator:checkOutCount,trigger: 'blur'}
                    ]
                },


                rules: {

                    name: [
                        {required: true, message: '请输入品名', trigger: 'blur'},
                    ],
                    goodstype: [
                        {required: true, message: '请选择种类', trigger: 'blur'},
                    ],
                    storage: [
                        {required: true, message: '请选择仓库', trigger: 'blur'},
                    ],
                    count: [
                        {required: true, message: '请输入数量', trigger: 'blur'},
                        {pattern: /^([1-9][0-9]*){1,4}$/,message: '数量必须为正整数字',trigger: "blur"},
                        {validator:checkCount,trigger: 'blur'}
                    ]
                }

            }
        },
        methods:{

            doSelectUser(val){
                this.tempUser = val;
            },

            confirmUser(){

                this.inGoodsForm.userName = this.tempUser.name;
                this.inGoodsForm.userId = this.tempUser.id;

                this.outGoodsForm.userName = this.tempUser.name;
                this.outGoodsForm.userId = this.tempUser.id;

                this.innerVisible = false;
            },

            selectGoodsCurrentChange(val) {
                this.currentRow = val;
            },

            goods_storage(row){
                let temp = this.storageData.find(item=>{
                    return item.id == row.storage
                })
                return temp && temp.name
            },

            goods_goodstype(row){
                let temp = this.goodstypeData.find(item=>{
                    return item.id == row.goodstype
                })
                return temp && temp.name
            },

            mod(row){

                this.centerDialogVisible = true;
                this.addOrUpdate = '修改物品信息';

                this.$nextTick(()=>{

                    //赋值到表单
                    this.form.id = row.id;
                    this.form.remark = row.remark;
                    this.form.name = row.name;
                    this.form.goodstype = row.goodstype;
                    this.form.count = row.count;
                    this.form.storage = row.storage;
                })
            },

            del(id){
                this.$axios.get(this.$httpUrl + '/goods/del?id='+id).then(res=>res.data).then(res=>{

                    if (res.code==200){
                        this.$message({
                            message: '删除成功！',
                            type: 'success'
                        });

                        this.loadPost();

                    }else{
                        this.$message({
                            message: '删除失败！',
                            type: 'error'
                        });
                    }
                })
            },

            resetForm() {
                this.$refs.form.resetFields();
            },

            resetInAndOutGoodsForm() {

                this.$refs.inGoodsForm.resetFields();
                this.inGoodsForm.userName = '';

                this.$refs.outGoodsForm.resetFields();
                this.outGoodsForm.userName = ''

            },
            handleClose(done) {
                this.$confirm('数据还未提交，确定关闭？')
                    .then(_ => {
                        done();
                    })
                    .catch(_ => {});
            },

            saveAdd(){

                this.$refs.form.validate((valid) => {
                    if (valid) {

                        if (this.form.id){
                            this.doMod();
                        }else{
                            this.doSave();
                        }

                    } else {
                        this.$message({
                            message: '请将物品信息填完整！',
                            type: 'warning'
                        });
                        return false;
                    }
                });

            },

            doMod(){
                this.$axios.post(this.$httpUrl + '/goods/mod',this.form).then(res=>res.data).then(res=>{

                    if (res.code==200){
                        this.$message({
                            message: '修改成功！',
                            type: 'success'
                        });

                        this.centerDialogVisible= false;
                        this.loadPost();

                    }else{
                        this.$message({
                            message: '修改失败！',
                            type: 'error'
                        });
                    }

                })
            },

            doSave(){
                this.$axios.post(this.$httpUrl + '/goods/save',this.form).then(res=>res.data).then(res=>{

                    if (res.code==200){
                        this.$message({
                            message: '添加成功！',
                            type: 'success'
                        });

                        this.centerDialogVisible= false;
                        this.loadPost();

                    }else{
                        this.$message({
                            message: '添加失败！',
                            type: 'error'
                        });
                    }
                })
            },

            addGoods(){
                this.centerDialogVisible = true;

                this.addOrUpdate = '添加物品';

                this.$nextTick(()=>{
                    this.resetForm()

                })
            },

            inGoods(){

                if (!this.currentRow.id){
                    this.$message.error("请先点击物品行选择物品");
                    return;
                };
                this.inGoodsDialogVisible = true;
                this.addOrUpdate = '入库';

                this.$nextTick(()=>{
                    this.resetInAndOutGoodsForm();
                    this.inGoodsForm.userName = '';
                })

                /*给表单赋值*/
                this.inGoodsForm.goodsName = this.currentRow.name;
                this.inGoodsForm.goodsType = this.currentRow.goodstype;
                this.inGoodsForm.storage = this.currentRow.storage;
                this.inGoodsForm.goods = this.currentRow.id;
                this.inGoodsForm.adminId = this.user.id;
                this.inGoodsForm.status = "inStorage"

            },

            outGoods(){
                if (!this.currentRow.id){
                    this.$message.error("请先点击物品行选择物品");
                    return;
                };
                this.outGoodsDialogVisible = true;
                this.addOrUpdate = '出库';

                this.$nextTick(()=>{
                    this.resetInAndOutGoodsForm();
                    this.outGoodsForm.userName = ''

                })

                this.outGoodsForm.goodsName = this.currentRow.name;
                this.outGoodsForm.goodsType = this.currentRow.goodstype;
                this.outGoodsForm.storage = this.currentRow.storage;
                this.outGoodsForm.goods = this.currentRow.id;
                this.outGoodsForm.adminId = this.user.id;
                this.outGoodsForm.status = "outStorage"

            },
            selectUser(){
                this.innerVisible = true;
            },

            doInGoods(){
                this.$axios.post(this.$httpUrl + '/record/inOrOutGoods',this.inGoodsForm).then(res=>res.data).then(res=>{

                    if (res.code==200){
                        this.$message({
                            message: '操作成功！',
                            type: 'success'
                        });
                        this.inGoodsDialogVisible= false;
                        this.loadPost();
                        this.resetInAndOutGoodsForm();

                    }else{
                        this.$message.error("操作失败，请填完整！")
                    }
                })
            },
            doOutGoods(){
                this.$axios.post(this.$httpUrl + '/record/inOrOutGoods',this.outGoodsForm).then(res=>res.data).then(res=>{

                    if (res.code==200){
                        this.$message({
                            message: '操作成功！',
                            type: 'success'
                        });
                        this.outGoodsDialogVisible= false;
                        this.loadPost();
                        this.resetInAndOutGoodsForm();

                    }else{
                        this.$message.error("操作失败，请填完整！")
                    }
                })
            },

            reset(){
                this.inputName='';
                this.selectStorage='';
                this.selectGoodstype='';

                this.loadPost()
            },

            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.pageNum = 1;
                this.pageSize = val;
                this.loadPost();

            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.pageNum = val;
                this.loadPost();
            },

            loadPost(){
                this.$axios.post(this.$httpUrl + '/goods/diyListPage',{
                    pageSize: this.pageSize,
                    pageNum: this.pageNum,

                    param:{
                        name: this.inputName,
                        storage: this.selectStorage + '',
                        goodstype: this.selectGoodstype + ''
                    }

                }).then(res=>res.data).then(res=>{
                    console.log(res);

                    if (res.code==200){
                        this.tableData = res.data
                        this.total = res.total
                    }else{
                        this.$message.error("获数据失败！")
                    }

                })
            },
            loadStorage(){
                    this.$axios.get(this.$httpUrl + '/storage/list').then(res=>res.data).then(res=>{

                        if (res.code==200){
                            this.storageData = res.data
                            this.total = res.total
                        }else{
                            this.$message.error("获数据失败！")
                        }

                    })
                },
            loadGoodstype(){
                this.$axios.get(this.$httpUrl + '/goodstype/list').then(res=>res.data).then(res=>{

                    if (res.code==200){
                        this.goodstypeData = res.data
                        this.total = res.total
                    }else{
                        this.$message.error("获数据失败！")
                    }

                })
            }

        },
        beforeMount() {
            this.loadStorage();
            this.loadGoodstype();

            this.loadPost();
        }
    }
</script>

<style scoped>
    .el-table-column{
        text-align: center;
        margin: auto;
    }
</style>